package com.hmall.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Serendipity-li
 * @Date: 2024/8/1 - 21:20
 * @Description: 自定义一个拦截器，获取用户信息并存入ThreadLocal中
 */
public class UserInfoInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头中user-info的信息
        String userId = request.getHeader("user-info");
        // 2.判断是否为空
        if (StrUtil.isNotBlank(userId)) {
            //3.不为空，则存放到ThreadLocal
             UserContext.setUser(Long.valueOf(userId));
        }
        //3.放行
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //等完整的一次请求完成之后，清楚用户信息
        UserContext.removeUser();
    }
}
